package com.brtbeacon.wx.demo.mapview;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.List;

public class MapRecordDatabase extends SQLiteOpenHelper {

    public final static String DB = "map_db";
    public final static String TABLE_MAP_RECORD = "map_record";

    public MapRecordDatabase(Context context) {
        super(context, DB, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(sql_create_table);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { }

    public List<MapRecord> getMapRecords() {
        SQLiteDatabase db = getReadableDatabase();
        Cursor cursor = db.rawQuery("SELECT id, url, name FROM " + TABLE_MAP_RECORD + " ORDER BY id DESC", null);
        List<MapRecord> mapRecords = new ArrayList<>();
        while (cursor.moveToNext()) {
            MapRecord record = new MapRecord();
            record.id = cursor.getInt(0);
            record.url = cursor.getString(1);
            record.name = cursor.getString(2);
            mapRecords.add(record);
        }
        cursor.close();
        return mapRecords;
    }

    public void removeMapRecord(int id) {
        SQLiteDatabase db = getWritableDatabase();
        db.delete(TABLE_MAP_RECORD, "id=?", new String[]{String.valueOf(id)});
    }

    public void updateMapRecord(MapRecord record) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("UPDATE " + TABLE_MAP_RECORD + " SET url=?, name=? WHERE id=?", new Object[]{ record.url, record.name, record.id});
    }

    public void addMapRecord(MapRecord record) {
        SQLiteDatabase db = getWritableDatabase();
        db.execSQL("INSERT INTO " +  TABLE_MAP_RECORD + "(url, name) VALUES(?,?)", new Object[] { record.url, record.name });
    }

    private String sql_create_table = "CREATE TABLE " + TABLE_MAP_RECORD + " (\n" +
            "    id   INTEGER PRIMARY KEY AUTOINCREMENT,\n" +
            "    url  TEXT,\n" +
            "    name TEXT\n" +
            ");";
}
